package com.dai.zhenfujin.addresslist.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;

import com.baidu.platform.comapi.map.J;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.adapter.EaseConversationAdapter2;
import com.dai.zhenfujin.bean.BlackBean;
import com.dai.zhenfujin.bean.ChatListBean;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.huanxin.EaseChat.NoticeChatRow;
import com.dai.zhenfujin.message.ChatActivity;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.view.EaseConversationList;
import com.dai.zhenfujin.visitingcard.app.adapter.MsgLisstAdapter;
import com.dai.zhenfujin.visitingcard.app.adapter.PersonalDetailsListviewAdapter2;
import com.google.gson.Gson;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMConversationListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.ui.EaseBaseFragment;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.dai.zhenfujin.Constants.EventConstants.PUBLISH_DYNAMIC;
import static com.dai.zhenfujin.http.HttpClient.RESULT;
import static com.dai.zhenfujin.http.HttpClient.RESULT2;
import static com.dai.zhenfujin.http.HttpClient.RET_CODE;

/**
 * conversation list fragment
 *
 */
public class EaseConversationListFragment extends EaseBaseFragment implements EMMessageListener {
    private final static int MSG_REFRESH = 2;
    protected EditText query;
    protected ImageButton clearSearch;
    protected boolean hidden;
    protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
    protected EaseConversationList conversationListView;
    protected FrameLayout errorItemContainer;

    protected boolean isConflict;

    protected EMConversationListener convListener = new EMConversationListener() {
        @Override
        public void onCoversationUpdate() {
            refresh();
        }
    };
    private EMConversation conversationChat;
    private List<EMConversation> emConversations;
    private  List<BlackBean.FollowListBean> chat_list = new ArrayList<>();
    private MsgLisstAdapter adapter;
    private int allMsgCount;
    private List<EMMessage> allMessages;

    //private List<EMConversation> list = new ArrayList<EMConversation>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ease_fragment_conversation_list, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initView() {
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        conversationListView = (EaseConversationList) getView().findViewById(R.id.list);
        query = (EditText) getView().findViewById(R.id.query);
        // button to clear content in search bar
        clearSearch = (ImageButton) getView().findViewById(R.id.search_clear);
        errorItemContainer = (FrameLayout) getView().findViewById(R.id.fl_error_item);
    }

    @Override
    protected void setUpView() {
        //加载消息列表
        Log.i("setUpView","------setUpView");
      //  conversationList.clear();
      //  emConversations = loadConversationList();
        //conversationList.clear();
        loadConversationList();

      //  adapter = new MsgLisstAdapter(getContext(), chat_list);
       // conversationListView.setAdapter(adapter);
       // getMsgList();


        if (listItemClickListener != null) {
            conversationListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    EMConversation conversation = conversationListView.getItem(position);
                    listItemClickListener.onListItemClicked(conversation);
                }
            });
        }

        EMClient.getInstance().addConnectionListener(connectionListener);

        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (null != conversationListView)
                conversationListView.filter(s);
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });

        conversationListView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard();
                return false;
            }
        });
    }

    private void getMsgList() {

    }


    protected EMConnectionListener connectionListener = new EMConnectionListener() {

        @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED
                    || error == EMError.USER_KICKED_BY_CHANGE_PASSWORD || error == EMError.USER_KICKED_BY_OTHER_DEVICE) {
                isConflict = true;
            } else {
                handler.sendEmptyMessage(0);
            }
        }

        @Override
        public void onConnected() {
            handler.sendEmptyMessage(1);
        }
    };
    private EaseConversationListItemClickListener listItemClickListener;

    protected Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    onConnectionDisconnected();
                    break;
                case 1:
                    onConnectionConnected();
                    break;

                case MSG_REFRESH: {
                  //  getMsgList();
                    loadConversationList();
                  //  conversationList.clear();
                   // conversationList.addAll(loadConversationList());
                   // conversationListView.init(conversationList);
                  //  conversationListView.refresh();
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * connected to server
     */
    protected void onConnectionConnected() {
        errorItemContainer.setVisibility(View.GONE);
    }

    /**
     * disconnected with server
     */
    protected void onConnectionDisconnected() {
        errorItemContainer.setVisibility(View.VISIBLE);
    }


    /**
     * refresh ui
     */
    public void refresh() {
        if (!handler.hasMessages(MSG_REFRESH)) {
            handler.sendEmptyMessage(MSG_REFRESH);
        }
    }

    /**
     * load conversation list
     *
     * @return +
     */
    protected List<EMConversation> loadConversationList() {
        new Thread(new Runnable(){
            @Override
            public void run() {
                Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();

                Log.i("setUpView---",conversations.size() + "");

                List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
                List<EMConversation> list = new ArrayList<>();

                Map<String, Object> params = new HashMap<>();
                Map<String, String> params2 = new HashMap<>();
                params2.put("page", 1 + "");
                params2.put("number", 30 + "");
                params.put("req_bd", params2);


                String json = HttpClient.post2(getActivity(),Constants.CHATLIST, params);
                if (!TextUtils.isEmpty(json)){
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        JSONObject json2 = jsonObject.getJSONObject(RESULT);
                        int res_code = json2.getInt(RET_CODE);
                        JSONObject result = jsonObject.getJSONObject(RESULT2);
                        if (res_code == 1){
                            JSONArray chat_list1 = result.getJSONArray("chat_list");
                            for (int i=0;i< chat_list1.length();i++) {
                                String friend_id =  chat_list1.getJSONObject(i).getString("friend_id");
                                String user_name =  chat_list1.getJSONObject(i).getString("user_name");
                                String user_logo =  chat_list1.getJSONObject(i).getString("user_logo");
                                if (!conversations.containsKey(friend_id) && !TextUtils.isEmpty(user_logo)){
                                    EMConversation  conversation = EMClient.getInstance().chatManager().getConversation(friend_id, EaseCommonUtils.getConversationType(1), true);
                                    conversations.put(friend_id,conversation);
                                    //头像
                                    SPUtils.saveConversionHeadPhoto(getContext(), friend_id, user_logo);
                                    //昵称
                                    SPUtils.saveConversionNickName(getContext(), friend_id, user_name);

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                synchronized (conversations) {
                    for (EMConversation conversation : conversations.values()) {
                        if (conversation.getAllMessages().size() != 0) {
                            sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                        }else {
                            sortList.add(new Pair<Long, EMConversation>(null, conversation));
                        }
                    }
                }

                try {
                    // Internal is TimSort algorithm, has bug
                    sortConversationByLastChatTime(sortList);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                for (Pair<Long, EMConversation> sortItem : sortList) {
                    list.add(sortItem.second);
                }

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("setUpView-----list----",list.size() + "");
                        if (null != conversationList) {
                            conversationList.clear();
                            conversationList.addAll(list);
                            conversationListView.init(conversationList);
                            conversationListView.refresh();
                        }
                    }
                });
            }
        }).start();

     return null;
    }

    /**
     * sort conversations according time stamp of last message
     * 
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }
    
   protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden && !isConflict) {
            refresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(this);
        if (!hidden) {
            refresh();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        EMClient.getInstance().chatManager().removeMessageListener(this);

    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(connectionListener);
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(isConflict){
            outState.putBoolean("isConflict", true);
        }
    }

    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        refresh();
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        for (EMMessage messageCmd : messages) {
            final EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) messageCmd.getBody();
            Logger.d("MessageFragment------EditCreateGroup-----" + cmdMsgBody.action() + "----MessageFragment");
            if (cmdMsgBody.action().equals(PUBLISH_DYNAMIC)) {  //动态提醒
                MessageEvent messageEventUpdateLabel = new MessageEvent();
                messageEventUpdateLabel.setMessageKey(PUBLISH_DYNAMIC);
                EventBus.getDefault().post(messageEventUpdateLabel);
            }
        }
    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {

    }

    @Override
    public void onMessageRecalled(List<EMMessage> messages) {

    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {

    }

    public interface EaseConversationListItemClickListener {
        /**
         * click event for conversation list
         * @param conversation -- clicked item
         */
        void onListItemClicked(EMConversation conversation);
    }
    
    /**
     * set conversation list item click listener
     * @param listItemClickListener
     */
    public void setConversationListItemClickListener(EaseConversationListItemClickListener listItemClickListener){
        this.listItemClickListener = listItemClickListener;
    }

}
